import pandas as pd
import os
import csv
import pandas as pd
import json


#将filelist中的文件使用规定好的处理df的流程进行读取
def fileTodf(file_list,type):
    list=[]
    for i in range(len(file_list)):
        func = globals()[type+"_deal"]
        # print(func,"func")
        df=(func(file_list[i]))
        list.append(df)
    df = pd.concat(list, ignore_index=True)
    df = df.sort_values(by=df.columns[0], ignore_index=True)
    
    return df

def long_term_ecg_deal(file):
    data = []
    with open(file, 'r', newline='') as file:
        reader = csv.reader(file)
        headers = next(reader)[0:7]
        for row in reader:

            data.append(row[0:7])

    # 将读取的数据转换为 Pandas DataFrame
    df = pd.DataFrame(data,columns=headers)
    #排序
    df.sort_values(by='ecg_timestamp',ascending=True,inplace=True)
    df['ecg_timestamp'] = df['ecg_timestamp'].str[0:13]
    # 打印 DataFrame，检查数据是否正确加载
    # print("转换的 DataFrame:",df.columns)
    # print(df)
    return df



# ecg转df
def ecg_deal(file):
    data = []
    with open(file, 'r', newline='') as file:
        reader = csv.reader(file)
        headers = next(reader)[0:5]
        for row in reader:

            data.append(row[0:5])

    # 将读取的数据转换为 Pandas DataFrame
    df = pd.DataFrame(data,columns=headers)
    #排序
    df.sort_values(by='ecg_timestamp',ascending=True,inplace=True)
    df['ecg_timestamp'] = df['ecg_timestamp'].str[0:13]
    # 打印 DataFrame，检查数据是否正确加载
    # print("转换的 DataFrame:",df.columns)
    # print(df)
    return df

#rrdata 转df
def rrdata_deal(file):
    data = []
    with open(file, 'r', newline='') as file:
        reader = csv.reader(file)
        next(reader)
        for row in reader:
            row.append('')
            row.append('')
            row.append('')
            row.append('')
            row.append('')
            row.append('')
            data.append(row[0:8])

            # print(row)
    # 将读取的数据转换为 Pandas DataFrame
    df = pd.DataFrame(data, columns=['timestamp','HR','rr1','rr2','rr3','rr4','rr5','rr6'],)
    df.sort_values(by='timestamp',ascending=True,inplace=True)
    df['timestamp'] = df['timestamp'].str[0:13]
    df['rr']=''
    df['rr'] = df[['rr1', 'rr2', 'rr3', 'rr4', 'rr5', 'rr6']].apply(lambda row: row.tolist(), axis=1)
    # 打印 DataFrame，检查数据是否正确加载
    # print("转换的 DataFrame:",df.columns)
    # print(df)
    return df



# ppg转df

def ppg_deal(file):
    df = pd.read_csv(file, sep='\t' , encoding='utf-8',engine='python')
    # df.sort_values(by='PPG_TIME', ascending=True, inplace=True)
    # print(df)
    return df


#rri转df

def rri_deal(file):
    '''

    :param file:
    :return:
    '''
    try:
        df = pd.read_csv(file, sep=',', header=None, encoding='utf-8')
        # 读取并处理第五列数据
        fifth_column = df.iloc[:, 5]  # 第五列的索引是4，因为索引从0开始计数

        # 准备存储数据的列表
        data = []

        # 遍历第五列的数据
        for k in fifth_column[1:-1]:  # 注意：这里可能需要根据实际情况调整切片范围
            for i in json.loads(k):
                timestamp = i['timeFrame']['timestamp']
                sqi = i['sqi']
                value = i['rri']['value']
                data.append([timestamp, sqi, value])

    # 创建 DataFrame
        df_rr = pd.DataFrame(data, columns=['timestamp', 'sqi', 'value'])
        df_rr.sort_values(by='timestamp', ascending=True, inplace=True)
        #去重
        df_rr.drop_duplicates(subset='timestamp', keep='first', inplace=True)
        #只选取sqi=0的行
        df_rr = df_rr[df_rr['sqi'] != 0]
        return df_rr
    except FileNotFoundError:
        print("文件 '{}' 不存在。".format(file))

    except Exception as e:
        print("处理数据时出错：{}".format(e))



# singwork 转df



def singlework_deal(file):
    '''

    :param file:
    :return:
    '''
    df = pd.read_csv(file, sep=',', encoding='utf-8', )

    df = df.loc[:, ['数据时间','活动名称', '活动.测量开始时间', '活动.测量结束时间','运动总时长', ]]
    # 将时间转换为时间戳13位整数
    df['timestamp'] = (pd.to_datetime(df['数据时间']).dt.tz_localize('Asia/Shanghai').dt.tz_convert('UTC').astype('int64') // 1000000)
    df.sort_values(by='timestamp', ascending=True, inplace=True)
    #去重复
    df.drop_duplicates(subset='timestamp', keep='first', inplace=True)
    return df



#singledetail 转df
def singledetail_deal(file):
    

    '''

    :param file:
    :return:
    '''
    df = pd.read_csv(file, sep=',', encoding='utf-8',)

    df=df.loc[:,['数据时间','速度','步频','心率']]
    df['timestamp'] = (pd.to_datetime(df['数据时间']).dt.tz_localize('Asia/Shanghai').dt.tz_convert('UTC').astype('int64') // 1000000)
    
    # df['timestamp'] = df['timestamp'].dt.tz_convert('Asia/Shanghai')
    df.sort_values(by='timestamp', ascending=True, inplace=True)
    return df


